﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.HtmlControls;
using System.Collections;
using DataAccess;
using com.chttl.ienc.bean;
using java.util;
using Microsoft.Reporting.WebForms;
using System.IO;
using Ionic.Zip;

namespace iEN.Report
{
    public partial class BillReport : System.Web.UI.Page
    {
        string sPeriod1 = "", sPeriod2 = "", sPeriod3 = "", sPeriod4 = "", sExpense1 = "", sExpense2 = "", sExpense3 = "", sExpense4 = "";
        System.Collections.ArrayList alBillModeBgn = new System.Collections.ArrayList();    //計費週期開始時間
        System.Collections.ArrayList alBillModeEnd = new System.Collections.ArrayList();    //計費週期結束時間
        System.Collections.ArrayList alBillModeExp = new System.Collections.ArrayList();    //計費週期費用

        //初始頁面
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.Page.IsPostBack)//先判斷是否已經登入過
            {
                if (Session["LoginName"] == null)
                {
                    Response.Write("<script>alert('請先登入！！');location.href='../Login.aspx';</script>");
                }

                //權限判斷
                //Operator : 可查詢、匯出、列印報表。   Session["SysAdmin"]=1
                //Director : 管理者，可使用所有功能。   Session["SysAdmin"]=2
                string sSysAdmin = Session["SysAdmin"].ToString();
                if (sSysAdmin != "1" && sSysAdmin != "2")
                {
                    ErrorMsg("您沒有使用此頁面的權限，請聯絡系統管理員！");
                    btnQuery.Visible = false;
                    return;
                }

                Session["FolderName"] = Session.SessionID.ToString();
                Intialize();    //初始化控制項
            }
        }

        /// <summary>
        /// 初始化控制項
        /// </summary>
        private void Intialize()
        {
            //取得大樓名稱
            ddlBuilding.Items.Clear();
            ddlBuilding.Items.Add("---");
            DataTable dtOrgGroup = new DBAccess().getOrgGroupTableByLevel(1);   //取得Level=1的大樓資訊
            for (int i = 0; i < dtOrgGroup.Rows.Count; i++)
            {
                ListItem li = new ListItem(dtOrgGroup.Rows[i]["_name"].ToString().Trim(), dtOrgGroup.Rows[i]["_id"].ToString());
                ddlBuilding.Items.Add(li);
            }
            ddlBuilding.SelectedIndex = 0;

            //取得目前DB的學年度資料
            ddlYear.Items.Clear();
            DataTable dtYear = new DBAccess().getYearOfBillingModeTable();      //取得學年度資料
            for (int i = 0; i < dtYear.Rows.Count; i++)
            {
                ListItem li = new ListItem(dtYear.Rows[i]["_year"].ToString().Trim(), dtYear.Rows[i]["_year"].ToString());
                ddlYear.Items.Add(li);
            }
            if (ddlYear.Items.Count > 0)
            {
                ddlBuilding.SelectedIndex = 0;
                LoadPeriod();   //載入某學年度的電費計算週期
                string sPeriodValue = ddlPeriod.SelectedItem.Value;     //查詢區間
                string[] s = sPeriodValue.Split('|');
                int iID = Convert.ToInt32(s[0]);                        //計費期間的代號
                DateTime dtBgnDate = Convert.ToDateTime(s[1]);          //計費開始時間
                DateTime dtEndDate = Convert.ToDateTime(s[2]);          //計費結束時間
                lblPeriod.Text = dtBgnDate.ToString("yyyy/MM/dd HH:mm:ss") + "~" + dtEndDate.ToString("yyyy/MM/dd HH:mm:ss");
            }

            //刪除當天前建立的資料夾
            string TempPath = this.MapPath("./Temp/");
            if (Directory.Exists(TempPath))
            {
                string[] TempChildFolder = Directory.GetDirectories(TempPath);
                for (int i = 0; i < TempChildFolder.Length; i++)
                {
                    try
                    {
                        DateTime dateCreate = Directory.GetCreationTime(TempChildFolder[i]);
                        TimeSpan ts = DateTime.Now.Subtract(dateCreate);
                        if (ts.TotalDays > 1)
                        {
                            Directory.Delete(TempChildFolder[i], true);
                        }
                    }
                    catch (Exception ex)
                    {
                        lblStatus.Text += ex.Message;
                    }
                }
            }
                
            btnQuery.Attributes["onclick"] = ";document.getElementById('Loading').style.visibility='visible';";
        }

        /// <summary>
        /// 重新選擇大樓
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlBuilding_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlFloor.Items.Clear();
            ddlFloor.Items.Add("---");
            if (ddlBuilding.SelectedItem.Text != "---")
            {
                string sID = ddlBuilding.SelectedItem.Value;
                DataTable dtOrgGroup = new DBAccess().getOrgGroupTableByLevel(2);  //取得Level=2的樓層資訊
                dtOrgGroup.DefaultView.Sort = " _name";
                dtOrgGroup = dtOrgGroup.DefaultView.ToTable();

                IEnumerable<DataRow> query = from r in dtOrgGroup.AsEnumerable()
                                             where sID.Contains(r.Field<Int32>("_parent_id").ToString())
                                             select r;
                foreach (DataRow r in query)
                {
                    ListItem li = new ListItem(r["_name"].ToString().Trim(), r["_id"].ToString());
                    ddlFloor.Items.Add(li);
                }
            }
            UpdatePanel3.Visible = false;
        }

        /// <summary>
        /// 重新選擇樓層
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlFloor_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlRoom.Items.Clear();
            ddlRoom.Items.Add("---");
            if (ddlFloor.SelectedItem.Text != "---")
            {
                string sID = ddlFloor.SelectedItem.Value;
                DataTable dtOrgGroup = new DBAccess().getOrgGroupTableByLevel(3);  //取得Level=3的寢室資訊
                dtOrgGroup.DefaultView.Sort = " _name";
                dtOrgGroup = dtOrgGroup.DefaultView.ToTable();

                IEnumerable<DataRow> query = from r in dtOrgGroup.AsEnumerable()
                                             where sID.Contains(r.Field<Int32>("_parent_id").ToString())
                                             select r;
                foreach (DataRow r in query)
                {
                    ListItem li = new ListItem(r["_name"].ToString().Trim(), r["_id"].ToString());
                    ddlRoom.Items.Add(li);
                }
            }
            UpdatePanel3.Visible = false;
        }

        /// <summary>
        /// 重新選擇學年度
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            //載入某學年度的電費計算週期
            LoadPeriod();
        }

        /// <summary>
        /// 選擇查詢區間
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlPeriod_SelectedIndexChanged(object sender, EventArgs e)
        {
            string sPeriodValue = ddlPeriod.SelectedItem.Value;     //查詢區間
            string[] s = sPeriodValue.Split('|');
            int iID = Convert.ToInt32(s[0]);                        //計費期間的代號
            DateTime dtBgnDate = Convert.ToDateTime(s[1]);          //計費開始時間
            DateTime dtEndDate = Convert.ToDateTime(s[2]);          //計費結束時間
            lblPeriod.Text = dtBgnDate.ToString("yyyy/MM/dd HH:mm:ss") + "~" + dtEndDate.ToString("yyyy/MM/dd HH:mm:ss");
        }

        /// <summary>
        /// 選擇報表格式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void rbPdf_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox cb = (CheckBox)sender;
            if (cb.ID == "rbPdf")
            {
                rbPdf.Checked = true;
                rbExcel.Checked = false;
            }
            else
            {
                rbPdf.Checked = false;
                rbExcel.Checked = true;
            }
        }

        /// <summary>
        /// 查詢
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            try
            {
                lblStatus.Text = "";
                if (ddlBuilding.SelectedItem.Text == "---")
                {
                    ErrorMsg("請選擇欲查詢的大樓！");
                    return;
                }

                string sPeriodValue = ddlPeriod.SelectedItem.Value;     //查詢區間
                string[] s = sPeriodValue.Split('|');
                int iID = Convert.ToInt32(s[0]);                        //計費期間的代號
                DateTime dtBgnDate = Convert.ToDateTime(s[1]);          //計費開始時間
                DateTime dtEndDate = Convert.ToDateTime(s[2]);          //計費結束時間

                #region 查每度電費
                alBillModeBgn = new System.Collections.ArrayList();
                alBillModeEnd = new System.Collections.ArrayList();
                alBillModeExp = new System.Collections.ArrayList();
                DataTable dtBillMode = new DBAccess().getBillingModeBillTableByID(iID);
                for (int i = 0; i < dtBillMode.Rows.Count; i++)
                {
                    Int32 ikwhBgn = Convert.ToInt32(dtBillMode.Rows[i]["_kwh_start"].ToString());
                    Int32 ikwhEnd = Convert.ToInt32(dtBillMode.Rows[i]["_kwh_end"].ToString());
                    double dExpense = Convert.ToDouble(dtBillMode.Rows[i]["_bill"].ToString());
                    alBillModeBgn.Add(ikwhBgn);
                    alBillModeEnd.Add(ikwhEnd);
                    alBillModeExp.Add(dExpense);

                    string skwhEnd = ikwhEnd.ToString();
                    if (skwhEnd == "9999999")
                        skwhEnd = "度以上";
                    else
                        skwhEnd = "~" + skwhEnd + "度";
                    switch (i)
                    {
                        case 0:
                            sPeriod1 = ikwhBgn.ToString() + skwhEnd;
                            sExpense1 = dExpense + "元";
                            break;
                        case 1:
                            sPeriod2 = ikwhBgn.ToString() + skwhEnd;
                            sExpense2 = dExpense + "元";
                            break;
                        case 2:
                            sPeriod3 = ikwhBgn.ToString() + skwhEnd;
                            sExpense3 = dExpense + "元";
                            break;
                        case 3:
                            sPeriod4 = ikwhBgn.ToString() + skwhEnd;
                            sExpense4 = dExpense + "元";
                            break;
                    }
                }
                #endregion

                if (ddlBuilding.SelectedItem.Text != "---" && ddlFloor.SelectedItem.Text == "---")  //大樓用電年報表
                {
                    int iBuilding = Convert.ToInt32(ddlBuilding.SelectedItem.Value);
                    BuildingReport(iBuilding, dtBgnDate, dtEndDate);
                }
                else if (ddlFloor.SelectedItem.Text != "---" && ddlRoom.SelectedItem.Text == "---")  //樓層用電年報表
                {
                    int iFloor = Convert.ToInt32(ddlFloor.SelectedItem.Value);
                    FloorReport(iFloor, dtBgnDate, dtEndDate);
                }
                else if (ddlRoom.SelectedItem.Text != "---")    //寢室用電年報表
                {
                    int iRoom = Convert.ToInt32(ddlRoom.SelectedItem.Value);
                    string sRoomName = ddlRoom.SelectedItem.Text;
                    RoomBillReport(iRoom, sRoomName, dtBgnDate, dtEndDate);
                }

                string FolderPath = this.MapPath("./Temp/" + Session["FolderName"].ToString() + "/");
                FileProcess(FolderPath, "空調用電報表.zip", true);
                ScriptManager.RegisterStartupScript(this, this.GetType(), "HideLoading", ";document.getElementById('Loading').style.visibility='hidden';", true);
            }
            catch (Exception ex)
            {
                lblStatus.Text += ex.Message;
                UpdatePanel3.Visible = false;
            }
        }

        private void BuildingReport(int iBuilding, DateTime dtBgnDate, DateTime dtEndDate)
        {
            //查該大樓的所有樓層
            DataTable dtOrgGroupFloor = new DBAccess().getOrgGroupTableByLevel(2);  //取得Level=2的樓層資訊
            IEnumerable<DataRow> queryFloor = from RowFloor in dtOrgGroupFloor.AsEnumerable()
                                              where iBuilding == RowFloor.Field<Int32>("_parent_id")
                                              orderby RowFloor.Field<string>("_name") ascending
                                              select RowFloor;
            foreach (DataRow RowFloor in queryFloor)
            {
                int iFloor = Convert.ToInt32(RowFloor["_id"].ToString());
                //查該樓層的所有寢室
                DataTable dtOrgGroup = new DBAccess().getOrgGroupTableByLevel(3);  //取得Level=3的寢室資訊
                IEnumerable<DataRow> query = from r in dtOrgGroup.AsEnumerable()
                                             where iFloor == r.Field<Int32>("_parent_id")
                                             select r;

                foreach (DataRow r in query)
                {
                    string sRoomName = r["_name"].ToString().Trim();
                    int iRoom = Convert.ToInt32(r["_id"].ToString());
                    RoomBillReport(iRoom, sRoomName, dtBgnDate, dtEndDate);
                }
            }
        }

        private void FloorReport(int iFloor, DateTime dtBgnDate, DateTime dtEndDate)
        {
            //查該樓層的所有寢室
            DataTable dtOrgGroup = new DBAccess().getOrgGroupTableByLevel(3);  //取得Level=3的寢室資訊
            IEnumerable<DataRow> query = from r in dtOrgGroup.AsEnumerable()
                                         where iFloor == r.Field<Int32>("_parent_id")
                                         select r;

            foreach (DataRow r in query)
            {
                string sRoomName = r["_name"].ToString().Trim();
                int iRoom = Convert.ToInt32(r["_id"].ToString());
                RoomBillReport(iRoom, sRoomName, dtBgnDate, dtEndDate);
            }
        }

        private void RoomBillReport(int iRoom, string sRoomName, DateTime dtBgnDate, DateTime dtEndDate)
        {
            string sBuildingName = ddlBuilding.SelectedItem.Text;   //大樓名稱
            string sBgnDate = dtBgnDate.ToString("yyyy/MM/dd");
            string sEndDate = dtEndDate.ToString("yyyy/MM/dd");
            
            decimal dTotalPower = 0;
            Int32 iTotalMoney = 0;
            iEN.Report.ReportDesign.StaticReportDataSet StaticReportDataSet = new ReportDesign.StaticReportDataSet();
            iEN.Report.ReportDesign.StaticReportDataSet.l_tag_etldataRow TempRow = (iEN.Report.ReportDesign.StaticReportDataSet.l_tag_etldataRow)(StaticReportDataSet.l_tag_etldata.NewRow());
            
            //查寢室電錶
            int iElectricMeter = new DBAccess().getElectricMeterByRoom(iRoom);
            if (iElectricMeter != -1)
            {
                //查用電資料
                DataTable dtFirst = new DBAccess().getTag_etldataTableFirstRecordOfYearByTagID(iElectricMeter, dtBgnDate);   //當年第一筆資料
                DataTable dtLast = new DBAccess().getTag_etldataTableLastRecordOfYearByTagID(iElectricMeter, dtEndDate);     //當年最後一筆資料
                if (dtFirst != null && dtLast != null && dtFirst.Rows.Count == 1 && dtLast.Rows.Count == 1)
                {
                    double dBgnRecord = Convert.ToDouble(dtFirst.Rows[0]["_last"].ToString());      //該年第一筆資料
                    double dEndRecord = Convert.ToDouble(dtLast.Rows[0]["_last"].ToString());       //該年最後一筆資料
                    decimal dPowerCount = (decimal)dEndRecord - (decimal)dBgnRecord;
                    dTotalPower += dPowerCount;
                    decimal dTotalBill = ComputeExpense_V2(alBillModeEnd, alBillModeExp, dPowerCount);
                    string sMoney = String.Format("{0:0}", dTotalBill > 0 ? dTotalBill : 0);
                    iTotalMoney = Convert.ToInt32(sMoney);

                    TempRow._start_time = Convert.ToDateTime(dtLast.Rows[0]["_start_time"].ToString());
                    TempRow._end_time = Convert.ToDateTime(dtLast.Rows[0]["_end_time"].ToString());
                    TempRow._first = dBgnRecord;
                    TempRow._last = dEndRecord;
                    TempRow._average = String.Format("{0:0.####}", dPowerCount);                    //_average作為使用電度數(度)
                    TempRow._id = Convert.ToInt32(dtLast.Rows[0]["_id"].ToString());
                    TempRow._datetime = sRoomName;                                                  //_datetime用來表示寢室
                    TempRow._device_id = Convert.ToInt32(dtLast.Rows[0]["_device_id"].ToString());
                    TempRow._tag_id = Convert.ToInt32(dtLast.Rows[0]["_tag_id"].ToString());
                    TempRow._count = sMoney;                                                        //_count作為金額
                }
                else
                    TempRow._datetime = sRoomName;
            }
            else    //該寢室查無電錶資料
            {
                TempRow._datetime = sRoomName;
            }
            StaticReportDataSet.l_tag_etldata.Addl_tag_etldataRow(TempRow);
                
            ReportViewer1.Reset();
            ReportViewer1.LocalReport.DataSources.Clear();
            ReportViewer1.LocalReport.ReportPath = "Report\\ReportDesign\\BillReport.rdlc";
            ReportViewer1.LocalReport.SetParameters(QueryReportParameter(
                "用電期間：" + ddlYear.SelectedItem.Text + "學年度 " + ddlPeriod.SelectedItem.Text + " (" + sBgnDate + " ~ " + sEndDate + ")",
                sBuildingName + "空調用電報表",
                sRoomName,
                String.Format("{0:0.####}", dTotalPower),
                String.Format("{0:0}", iTotalMoney),
                sPeriod1,
                sPeriod2,
                sPeriod3,
                sPeriod4,
                sExpense1,
                sExpense2,
                sExpense3,
                sExpense4
                ));
            ReportViewer1.LocalReport.DataSources.Add(new ReportDataSource("ienc_customer_ncku1DataSet", (DataTable)StaticReportDataSet.l_tag_etldata));

            string FolderPath = this.MapPath("./Temp/" + Session["FolderName"].ToString() + "/");
            string sReportFormat = "excel";
            string sExtension = "xls";
            if (rbPdf.Checked)
            {
                sReportFormat = "pdf";
                sExtension = "pdf";
            }
            string FileName = sBuildingName + sRoomName + "-空調用電報表" + "." + sExtension;
            if (!ExportReport(ReportViewer1, FolderPath, FileName, sReportFormat)) ErrorMsg("部分報表匯出失敗！");
        }

        private ReportParameter[] QueryReportParameter(string sDate, string sReportName, string sRoom, string sTotalPower, string sTotalMoney, 
            string sPeriod1, string sPeriod2, string sPeriod3, string sPeriod4, string sExpense1, string sExpense2, string sExpense3, string sExpense4)
        {
            ReportParameter[] ReportParameter = new ReportParameter[14];
            ReportParameter[0] = new ReportParameter("Report_Parameter_Date", sDate);
            ReportParameter[1] = new ReportParameter("Report_Parameter_ReportName", sReportName);
            ReportParameter[2] = new ReportParameter("Report_Parameter_Room", sRoom);
            ReportParameter[3] = new ReportParameter("Report_Parameter_TotalPower", sTotalPower);
            ReportParameter[4] = new ReportParameter("Report_Parameter_TotalMoney", sTotalMoney);
            ReportParameter[5] = new ReportParameter("Report_Parameter_PrintDate", "列印日期：" + DateTime.Now.ToString("yyyy/MM/dd"));
            ReportParameter[6] = new ReportParameter("Report_Parameter_Period1", sPeriod1);
            ReportParameter[7] = new ReportParameter("Report_Parameter_Period2", sPeriod2);
            ReportParameter[8] = new ReportParameter("Report_Parameter_Period3", sPeriod3);
            ReportParameter[9] = new ReportParameter("Report_Parameter_Period4", sPeriod4);
            ReportParameter[10] = new ReportParameter("Report_Parameter_Expense1", sExpense1);
            ReportParameter[11] = new ReportParameter("Report_Parameter_Expense2", sExpense2);
            ReportParameter[12] = new ReportParameter("Report_Parameter_Expense3", sExpense3);
            ReportParameter[13] = new ReportParameter("Report_Parameter_Expense4", sExpense4);
            return ReportParameter;
        }

        private bool ExportReport(ReportViewer ReportViewerExport, string absoluteFolderPath, string FileName, string ExportType)
        {
            try
            {
                if (!Directory.Exists(absoluteFolderPath))
                {
                    Directory.CreateDirectory(absoluteFolderPath);
                }
                string FilePath = absoluteFolderPath + FileName;

                Warning[] warnings;
                string[] streamids;
                string mimeType;
                string encoding;
                string filenameExtension;

                byte[] bytes = ReportViewerExport.LocalReport.Render(
                    ExportType, null, out mimeType, out encoding, out filenameExtension,
                    out streamids, out warnings);

                FileStream MyFileStream = new FileStream(FilePath, FileMode.Create);
                long FileSize;
                FileSize = MyFileStream.Length;
                MyFileStream.Write(bytes, 0, (int)bytes.Length);
                MyFileStream.Flush();
                MyFileStream.Close();
                return true;
            }
            catch (Exception ex)
            {
                lblStatus.Text += ex.Message;
                return false;
            }
        }

        private void FileProcess(string absoluteFolderPath, string FullFileName, bool IsCompress)    //資料夾所有檔案壓縮，或資料夾所有檔案導出下載
        {
            try
            {
                if (Directory.Exists(absoluteFolderPath))
                {
                    if (!IsCompress)  //不壓縮打包 
                    {
                        string[] FileNamePath = Directory.GetFiles(absoluteFolderPath);
                        for (int i = 0; i < FileNamePath.Length; i++)
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "output" + i.ToString(), ";window.open('./Download.aspx?FilePath=" + Server.UrlEncode(FileNamePath[i]) + "','Window" + i.ToString() + "');", true);
                        }
                    }
                    else//壓縮打包
                    {
                        string[] FileNamePath = Directory.GetFiles(absoluteFolderPath);
                        if (FileNamePath.Length == 0)
                            return;
                        //Response.Clear();
                        //Response.BufferOutput = false;  // for large files
                        //Response.ContentType = "application/zip";
                        //Response.AddHeader("content-disposition", "filename=" + HttpUtility.UrlEncode(FullFileName, System.Text.Encoding.UTF8));

                        using (ZipFile zip = new ZipFile(System.Text.Encoding.Default))
                        {
                            for (int i = 0; i < FileNamePath.Length; i++)
                            {
                                zip.AddFile(FileNamePath[i], "files");
                            }
                            //zip.Save(Response.OutputStream);
                            zip.Save(absoluteFolderPath + FullFileName);
                        }
                        //Response.Close();

                        for (int i = 0; i < FileNamePath.Length; i++)
                        {
                            File.Delete(FileNamePath[i]);
                        }
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "output1", ";window.open('./Download.aspx?FilePath=" + Server.UrlEncode(absoluteFolderPath + FullFileName) + "','Window1')", true);
                    }
                }
            }
            catch (Exception ex)
            {
                lblStatus.Text += ex.Message;
                return;
            }
        }

        /// <summary>
        /// 載入某學年度的電費計算週期
        /// </summary>
        private void LoadPeriod()
        {
            try
            {
                ddlPeriod.Items.Clear();
                int iYear = Convert.ToInt32(ddlYear.SelectedItem.Value);
                DataTable dtOrgGroup = new DBAccess().getBillingModeTableByYear(iYear);
                IEnumerable<DataRow> query = from r in dtOrgGroup.AsEnumerable()
                                             where iYear == r.Field<Int32>("_year")
                                             select r;
                foreach (DataRow r in query)
                {
                    int iMode = Convert.ToInt16(r["_mode"].ToString());
                    string sPeriod = r["_id"].ToString() + "|" + r["_begin_time"].ToString() + "|" + r["_end_time"].ToString();
                    string sPeriodName = "";
                    switch (iMode)
                    {
                        case 1:
                            sPeriodName = "上學期";
                            break;
                        case 2:
                            sPeriodName = "下學期";
                            break;
                        case 3:
                            sPeriodName = "暑假";
                            break;
                        case 4:
                            sPeriodName = "寒假";
                            break;
                    }
                    ListItem li = new ListItem(sPeriodName, sPeriod);
                    ddlPeriod.Items.Add(li);
                }
            }
            catch (Exception exc)
            {
                lblStatus.Text += exc.Message;
                UpdatePanel3.Visible = false;
            }
        }

        /// <summary>
        /// 計算電費
        /// </summary>
        /// <param name="alBillModeEnd"></param>
        /// <param name="alBillModeExp"></param>
        /// <param name="dTotalPower"></param>
        private decimal ComputeExpense(System.Collections.ArrayList alBillModeEnd, System.Collections.ArrayList alBillModeExp, decimal dTotalPower)
        {
            decimal dTotalExpense = 0;  //紀錄電量
            decimal dUnComputePower=0;  //紀錄未計算的用電量
            for (int i = 0; i < alBillModeEnd.Count; i++)
            { 
                decimal dBillModeEnd=Convert.ToDecimal(alBillModeEnd[i].ToString());
                decimal dExpense=Convert.ToDecimal(alBillModeExp[i].ToString());
                if (dTotalPower > dBillModeEnd)
                {
                    if (i == 0)
                        dTotalExpense += (dBillModeEnd * dExpense);
                    else
                    {
                        decimal dPreBillModeEnd = Convert.ToDecimal(alBillModeEnd[i - 1].ToString());   //上一個電費級距
                        dTotalExpense += ((dBillModeEnd - dPreBillModeEnd) * dExpense);
                    }
                    dUnComputePower = dTotalPower - dBillModeEnd;
                }
                else
                {
                    if (i == 0)
                        dTotalExpense += (dTotalPower * dExpense);
                    else
                    {
                        decimal dPreBillModeEnd = Convert.ToDecimal(alBillModeEnd[i - 1].ToString());   //上一個電費級距
                        dTotalExpense += ((dTotalPower - dPreBillModeEnd) * dExpense);
                    }
                    dUnComputePower = 0;
                }

                if (i == alBillModeEnd.Count - 1 && dUnComputePower > 0)    //用電量超過所有的級距，直接以最高級距的錢計算
                {
                    dTotalExpense += (dUnComputePower * dExpense);
                }
            }

            return dTotalExpense;
        }

        /// <summary>
        /// 計算電費
        /// </summary>
        /// <param name="alBillModeEnd"></param>
        /// <param name="alBillModeExp"></param>
        /// <param name="dTotalPower"></param>
        private decimal ComputeExpense_V2(System.Collections.ArrayList alBillModeEnd, System.Collections.ArrayList alBillModeExp, decimal dTotalPower)
        {
            decimal dTotalExpense = 0;  //紀錄電量
            decimal dUnComputePower = 0;  //紀錄未計算的用電量
           
            dUnComputePower = dTotalPower;

            for (int i = 0; i < alBillModeEnd.Count; i++)
            {
                decimal dBillModeEnd = Convert.ToDecimal(alBillModeEnd[i].ToString());
                decimal dExpense = Convert.ToDecimal(alBillModeExp[i].ToString());

                
                if (dTotalPower > dBillModeEnd)
                {

                    if (i == 0)
                        dTotalExpense += (dBillModeEnd * dExpense);
                    else
                    {
                        decimal dPreBillModeEnd = Convert.ToDecimal(alBillModeEnd[i - 1].ToString());   //上一個電費級距
                        dTotalExpense += ((dBillModeEnd - dPreBillModeEnd) * dExpense);
                    }
                    dUnComputePower = dTotalPower - dBillModeEnd;
                }
                else
                {
                    dTotalExpense += (dUnComputePower * dExpense);
                    break;
                    //if (i == 0)
                    //    dTotalExpense += (dTotalPower * dExpense);
                    //else
                    //{
                    //    decimal dPreBillModeEnd = Convert.ToDecimal(alBillModeEnd[i - 1].ToString());   //上一個電費級距
                    //    dTotalExpense += ((dTotalPower - dPreBillModeEnd) * dExpense);
                    //}
                    //dUnComputePower = 0;
                }

                if (i == alBillModeEnd.Count - 1 && dUnComputePower > 0)    //用電量超過所有的級距，直接以最高級距的錢計算
                {
                    dTotalExpense += (dUnComputePower * dExpense);
                }
            }

            return dTotalExpense;
        }

        /// <summary>
        /// 網頁show messagebox
        /// </summary>
        /// <param name="Msg"></param>
        private void ErrorMsg(string Msg)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", ";alert('" + Msg + "');", true);
            return;
        }

    }
}